﻿layui.use(['laydate'], function () {
    var laydate = layui.laydate;
    var $ = layui.$;
    var table = layui.table;
    var form = layui.form;
    var laypage = layui.laypage;
    laydate.render({
        elem: '#StartSheepBir',
    });
    laydate.render({
        elem: '#EndSheepBir'
    });

    var token = window.localStorage.getItem('token');

    // 可视耳号超链接事件
    function addLink(data) {
        var addLink = data.earNnumber;
        if ('' == addLink || null == addLink || undefined == addLink) {
            return '';
        }
        if (addLink.length > 0) {
            return `<a class="layui-table-link" lay-event="link" href="/IAMH/ArchivesSheepDetailPage?id=${data.id}">${data.earNnumber}</a>`;
        }
    }
    // 羊只品种
    $(document).ready(function () {
        //var url = 'http://localhost:5282/api/Archives/GetSheepBreeds';
        var url = 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/GetSheepBreeds';
        $.ajax({
            url: '/HttpClient/Get?url=' + url, // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                $.each(res, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.value).text(item.value);
                    $('#sheepBreed').append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });

    var data = [];
    // 栋舍
    $(document).ready(function () {
        var url = 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/CootList';
        $.ajax({
            url: '/HttpClient/Get?url=' + url, // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                data = res;
                $.each(res, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.name).text(item.name);
                    $('#cottageId').append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });

    // 栋舍栏位二级联动
    form.on('select(cottageIdSelect)', function (datas) {
        var id = 0;
        $.each(data, function (index, item) {
            if ($("#cottageId").val() == item.name) {
                id = item.id;
            }
        });

        //监听到了下拉框选择的选项，传递过来
        $.get({
            url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/FieidList', // 后端枚举数据接口地址
            data: {
                id: id
            },
            dataType: "json",
            success: function (res) {
                $("#fieId").empty();
                var option = '<option value=" ">' + "请选择" + '</option>';
                $("#fieId").append(option);
                $.each(res, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.name).text(item.name);
                    $('#fieId').append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });

    // 羊只生长阶段
    $(document).ready(function () {
        var url = 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/GetGrowthStage';
        $.ajax({
            url: '/HttpClient/Get?url=' + url, // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                $.each(res, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.value).text(item.value);
                    $('#growthStage').append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });
    // 羊只类型
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/GetSheepSpecies', // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                $.each(res, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.value).text(item.value);
                    $('#sheepType').append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });
    // 基因等级
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/GetGeneticGrade', // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                $.each(res, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.value).text(item.value);
                    $('#geneticGrade').append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });
    // 生产等级
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/GetProductionGrade', // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                $.each(res, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.value).text(item.value);
                    $('#productionGrade').append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });
    // 繁殖状态
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/GetReproductiveState', // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                $.each(res, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.value).text(item.value);
                    $('#reproductiveState').append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });
    // 在场状态
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/GetPresenceStatus', // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                $.each(res, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.value).text(item.value);
                    $('#presence').append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });
    var pageSize = 15; // 每页显示条数
    //获取列表
    function getListData(pageIndex) {
        var requestData = {
            url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesPageList',
            //url: 'http://localhost:5282/api/Archives/ArchivesPageList',
            parameters: {
                size: pageSize,
                index: pageIndex,
                earnumber: $("#earNumber").val() || "",
                electronicearnumber: $("#electronicEarNumber").val() || "",
                sheepbreed: $("[name=sheepBreed]").val() || "",
                sheepgender: $("[name=sheepGender]").val() || 2,
                startsheepbir: $("[name=StartSheepBir]").val() || "",
                endsheepbir: $("[name=EndSheepBir]").val() || "",
                presence: $("[name=presence]").val() || "",
                growthstage: $("[name=growthStage]").val() || "",
                sheeptype: $("[name=sheepType]").val() || "",
                cottageid: $("[name=cottageId]").val() || "",
                field: $("[name=fieId]").val() || "",
                reproductivestate: $("[name=reproductiveState]").val() || "",
                startstatusdays: $("[name=startStatusDays]").val() || 0,
                endstatusdays: $("[name=endStatusDays]").val() || 0,
                productiongrade: $("[name=productionGrade]").val() || "",
                salesgrade: $("[name=salesGrade]").val() || "",
                geneticgrade: $("[name=geneticGrade]").val() || "",
                fatherearnumber: $("[name=fatherEarNumber]").val() || "",
                motherearnumber: $("#motherEarNumber").val() || "",
            },
        };
        //console.log(requestData);
        //var url = "http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesPageList";
        //ajax后台交互
        $.ajax({
            //url: 'http://localhost:5282/api/Archives/ArchivesPageList',
            //url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesPageList',
            url: '/HttpClient/GetParam',
            type: 'get',
            contentType: 'application/json',
            dataType: 'json',
            data: requestData,
            //data: {
            //    Size: pageSize,
            //    Index: pageIndex,
            //    EarNumber: $("#earNumber").val() || "",
            //    ElectronicEarNumber: $("#electronicEarNumber").val() || "",
            //    SheepBreed: $("[name=sheepBreed]").val() || "",
            //    SheepGender: $("[name=sheepGender]").val() || 2,
            //    StartSheepBir: $("[name=StartSheepBir]").val() || "",
            //    EndSheepBir: $("[name=EndSheepBir]").val() || "",
            //    Presence: $("[name=presence]").val() || "",
            //    GrowthStage: $("[name=growthStage]").val() || "",
            //    SheepType: $("[name=sheepType]").val() || "",
            //    CottageId: $("[name=cottageId]").val() || 0,
            //    FieId: $("[name=fieId]").val() || 0,
            //    ReproductiveState: $("[name=reproductiveState]").val() || "",
            //    StartStatusDays: $("[name=startStatusDays]").val() || 0,
            //    EndStatusDays: $("[name=endStatusDays]").val() || 0,
            //    ProductionGrade: $("[name=productionGrade]").val() || "",
            //    SalesGrade: $("[name=salesGrade]").val() || "",
            //    GeneticGrade: $("[name=geneticGrade]").val() || "",
            //    FatherEarNumber: $("[name=fatherEarNumber]").val() || "",
            //    MotherEarNumber: $("#motherEarNumber").val() || "",
            //},
            success: function (res) {
                console.log(res);
                table.render({
                    //挂载的表格id
                    elem: '#ID-table-demo-setRowChecked',
                    cols: [[
                        { type: 'checkbox', width: 60, fixed: 'center', unresize: true, align: 'center' },
                        { field: 'number', type: 'numbers', title: '序号', width: 60, fixed: 'center', unresize: true, align: 'center', templet: '#zizeng' },
                        { field: 'earNnumber', title: '可视耳号', width: 120, align: 'center', templet: addLink },
                        {
                            field: 'electronicEarNumber', title: '电子耳号', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.electronicEarNumber == null || data.electronicEarNumber == "") { return "---"; }
                                else { return data.electronicEarNumber; }
                            },
                        },
                        { field: 'sheepBreed', title: '品种', width: 120, align: 'center' },
                        {
                            field: 'sheepGender', title: '性别', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.sheepGender == true) return '公';
                                if (data.sheepGender == false) return '母';
                            },
                        },
                        { field: 'sheepBir', title: '出生日期', width: 120, align: 'center', templet: function (data) { return data.sheepBir.substring(0, 10) } },
                        { field: 'dayAge', title: '日龄', width: 120, align: 'center' },
                        { field: 'monthAge', title: '月龄', width: 120, align: 'center' },
                        {
                            field: 'presence', title: '在场状态', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.presence == null || data.presence == "") { return "---"; }
                                else { return data.presence; }
                            },
                        },
                        {
                            field: 'growthStage', title: '阶段', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.growthStage == null || data.growthStage == "") { return "---"; }
                                else { return data.growthStage; }
                            },
                        },
                        { field: 'sheepType', title: '类型', width: 120, align: 'center' },
                        {
                            field: 'cottageId', title: '栋舍', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.cottageId == "0" || data.cottageId == "" || data.cottageId == null) { return "---"; }
                                else { return data.cottageId; }
                            }
                        },
                        {
                            field: 'field', title: '栏位', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.field == "0" || data.field == "" || data.field == null) { return "---"; }
                                else { return data.field; }
                            }
                        },
                        {
                            field: 'reproductiveState', title: '繁殖状态', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.reproductiveState == null || data.reproductiveState == "") { return "---"; }
                                else { return data.reproductiveState; }
                            }
                        },
                        {
                            field: 'pregnancyTest', title: '是否妊检', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.pregnancyTest == true) return '已妊检';
                                else return '未妊检';
                            },
                        },
                        {
                            field: 'statusDays', title: '状态天数', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.statusDays == null || data.statusDays == "") return '---';
                                else return data.statusDays;
                            },
                        },
                        {
                            field: 'productionGrade', title: '生产等级', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.productionGrade == null || data.productionGrade == "") return "未定级";
                                else return data.productionGrade;
                            }
                        },
                        {
                            field: 'salesGrade', title: '销售等级', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.salesGrade == null || data.salesGrade == "") return "未定级";
                                else return data.salesGrade;
                            }
                        },
                        {
                            field: 'geneticGrade', title: '基因等级', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.geneticGrade == null || data.geneticGrade == "") return "未定级";
                                else return data.geneticGrade;
                            }
                        },
                        { field: 'birthWeight', title: '出生重', width: 120, align: 'center' },
                        {
                            field: 'weaningWeigh', title: '断奶重', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.weaningWeigh == null || data.weaningDate == "") return '---';
                                else return data.weaningWeigh;
                            },
                        },
                        {
                            field: 'weaningDate', title: '断奶日期', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.weaningDate != null && data.weaningDate != "") return data.weaningDate.substring(0, 10);
                                else return "---";
                            }
                        },
                        {
                            field: 'weaningAge', title: '断奶日龄', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.weaningAge == "0") return '---';
                                else return data.weaningAge;
                            },
                        },
                        {
                            field: 'fatherEarNumber', title: '父耳号', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.fatherEarNumber == null || data.fatherEarNumber == "") return '---';
                                else return data.fatherEarNumber;
                            },
                        },
                        {
                            field: 'motherEarNumber', title: '母耳号', width: 120, align: 'center',
                            templet: function (data) {
                                if (data.motherEarNumber == null || data.motherEarNumber == "") return '---';
                                else return data.motherEarNumber;
                            },
                        },
                        { title: '操作', width: 120, align: 'center', templet: '#barDemo', fixed: 'right', unresize: true },
                    ]],
                    toolbar: '#demo-toolbar-setRowChecked',
                    data: res.datas
                });
                //分页
                laypage.render({
                    //挂载的分页id
                    elem: 'pagesbox',
                    count: res.totalCount,
                    limit: pageSize,
                    curr: pageIndex,
                    limits: [15, 20, 30],
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                    jump: function (obj, first) {
                        if (!first) {
                            pageSize = obj.limit;
                            getListData(obj.curr);
                        }
                    }
                });
            }
        });
    }
    // 查询方法
    $('#searchBtn').on('click', function () {
        getListData(1);
    });
    // 单删除
    function deleteData(id) {
        $.ajax({
            url: `http://10.31.60.18:8000/ArchivesSetRout/api/Archives/ArchivesDelete?Id=${id}`,
            type: 'delete',
            success: function (res) {
                if (res > 0) {
                    layer.msg('删除成功');
                    getListData(1);
                } else {
                    layer.msg('删除失败');
                }
            },
            error: function () {
                layer.msg('删除请求失败');
            }
        });
    }
    // 监听工具条，实现删除功能
    table.on('tool(ID-table-demo-setRowChecked)', function (obj) {
        var data = obj.data;
        if (obj.event == 'edit') {
            if (data.sheepType == "种公") {
                window.location.href = '/IAMH/ArchivesUpdateMalePage?Id=' + data.id;
            }
            else if (data.sheepType == "种母") {
                window.location.href = '/IAMH/ArchivesUpdateFemalePage?Id=' + data.id;
            }
            else if (data.sheepType == "后裔") {
                window.location.href = '/IAMH/ArchivesUpdateDescendentPage?Id=' + data.id;
            }
        }
        if (obj.event == 'delete') {
            layer.confirm('确定删除吗？', function (index) {
                deleteData(data.id); // 传递正确的数据项ID
                layer.close(index);
            });
        }
    });
    // 初始化加载数据
    getListData(1);
})